<script setup>

import {deletePost, getCourses} from "@/api/post.js";
import {onMounted, ref} from "vue";
import router from "@/router/index.js";


const postList = ref([]);

router.afterEach(() =>{
  window.location.reload();
})
function getPostList() {
  getCourses()
    .then((res) => {
      postList.value = res.data.courses;
    })
    .catch(e => console.log(e));
}
function confirmDelete(id){
  if (window.confirm("确定删除？")) {
    deletePost(id)
      .then(() => {
        console.log('删除成功id=' + id)
        // 这种方式会刷新整个页面，如果要更优雅的解决方案，可以使用 Pinia 的状态管理方案，也就是之前用过的 store
        router.go(0)

      })
  }
}
onMounted(() => {
  // component is now mounted.
  getPostList();
})

</script>


<template>
      <h1>课程管理</h1>
      <div class="card">
        <RouterLink to="/backend/course-add">
          <el-button style="margin-top:30px;float: right;" type="danger">Add</el-button>
        </RouterLink>
      </div>

      <div class="post">
        <table>
          <thead>
          <tr>
            <th style="width: 10%;">ID</th>
            <th style="width: 40%;">Title</th>
            <th style="width: 20%;">Created_at</th>
            <th style="width: 15%;">Action</th>
            <th style="width: 15%;">Action</th>
            <!-- 可以根据需要添加更多的表头 -->
          </tr>
          </thead>
          <tbody>
          <tr v-for="courses in postList" :key="courses.id">
            <td>
              {{ courses.courseId }}
            </td>
            <td>
              <RouterLink :to="`/backend/course-show/${courses.courseId}`">
                {{ courses.title }}
              </RouterLink>
            </td>
            <td>{{ courses.createdAt }}</td>
            <td @click="confirmDelete(courses.courseId)">删除</td>
            <td>
              <RouterLink :to="`/backend/course-edit/${courses.courseId}`">
                修改
              </RouterLink>
            </td>
            <!-- 根据需要显示更多的数据字段 -->
          </tr>
          </tbody>
        </table>
      </div>


</template>

<style>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}
th {
  background-color: #f2f2f2;
}
</style>
